package com.lucky.passport.controller;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.lucky.passport.ex.ServiceException;
import com.lucky.passport.mapper.UsersMapper;
import com.lucky.passport.web.JsonResult;
import com.lucky.passport.web.ServiceCode;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Random;
import java.util.Set;

@RestController
@Slf4j
@Api(tags = "短信注册")
public class SMSController {
    public static Integer code;

    @Autowired
    private UsersMapper usersMapper;

    @RequestMapping("/sendSMS")
    public JsonResult send(String phone){
        if(usersMapper.getByPhone(phone)>0){
            return JsonResult.fail(ServiceCode.ERR_INSERT,"该手机号已被绑定");
        }
        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //共有7处地方需要修改
        //修改1 ：管理-->控制台首页中能查到accountSId
        String accountSId = "8aaf0708842397dd018464b06c7215bb";
        //修改2 ：管理-->控制台首页中能查到accountToken
        String accountToken = "3dba869ec3a946d5890c0ad18a17012a";
        //修改3 ：管理-->应用管理-->应用列表-->应用01-->应用管理,查看appId
        String appId = "8aaf0708842397dd018464b06d4a15c2";
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        //修改4 ：修改接收短信的手机号，手机号要在后台添加进去
        String to = phone;
        //修改5 ：templateId改成1
        String templateId= "1";
        //修改6 ：
        Random random=new Random();
        Integer r = random.nextInt(1000)+8000;
        code = r;
        String[] datas = {r.toString(),"1"};
        String subAppend="1234";  //可选 扩展码，四位数字 0~9999

        int i= random.nextInt(1000000)+1;
        String reqId="q12qw"+ i;  //可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复
        //HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
        //修改7 ：修改reqId为新的
        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas,subAppend,reqId);


        return JsonResult.ok("发送成功!");
    }
}
